define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'jstreec', 'editable'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init();
            this.table.first();
            this.table.second();
        },
        table: {
            first: function () {    // 栏目目录树显示
				Controller.api.bindevent();
				getTree();
				//点击栏目打开对应的文章
				$(document).on("click", ".jstree-anchor", function () {
					var columnId = $(this).attr("id");					
					var i = columnId.lastIndexOf("_");
					var column_id = Number(columnId.substr(0,i));
					$("#add_article").attr("href", "article/add?column_id=" + column_id);  //给添加按钮赋打开链接
					$("#myTabContent2 .form-commonsearch input[name='column_id']").val(column_id); 	//栏目文章搜索
					$("#myTabContent2 .btn-refresh").trigger("click");
				});					

				//生成栏目目录树
	        	function getTree(isShowEdit = 0){
	        		var ind = layer.load();
	        		var url = 'Column/tree';
					data = {'isShowEdit': isShowEdit};
	        		$.ajax({
	        			url: url,
	                    type: 'post',
	                    data: data,
	                    dataType: 'json',
	                    success: function (ret) {
	                		layer.close(ind);
	                		$("#treeview").jstree("destroy");							
	                    	Controller.api.rendertree(ret);
	                	}
	                });
	        	}

				//显示隐藏目录修改按钮
				$(document).on("click", ".edit_column", function () {
	                $("edit").fadeToggle();
	            });

				//点击刷新栏目列表
				$(document).on("click", ".one_refresh", function () {
					var ind=layer.load();
					$("#myTabContent2 .form-commonsearch input[name='column_id']").val('');     	    //清空Process_id选项
					$("#myTabContent2 .btn-refresh").trigger("click");
					getTree();
					layer.close(ind);
	        	});
				//编辑成功后刷新栏目列表
				$(document).on("click", "#one_refresh", function () {
					var ind=layer.load();
					$("#myTabContent2 .form-commonsearch input[name='column_id']").val('');     	    //清空Process_id选项
					$("#myTabContent2 .btn-refresh").trigger("click");
					getTree(1);
					layer.close(ind);
	        	});

				$(document).on("click", ".del", function (e) {
	        		id = e.target.id;
					ids = $(this).attr("id");
					top.layer.confirm('确定删除栏目【'+e.target.dataset.name+'】？', {
	                    btn: ["确定","取消"],         //按钮
	                }, function(index){
	                	layer.close(index);
	                	$(".layui-layer-btn1").click();
	                	layer.load();
	                    $.ajax({
	                        url: "column/del",
	                        type: "post",
	                        data: {ids: id},
	                        dataType: "json",
	                        success: function (ret) {
								Layer.closeAll();
	                        	top.layer.close(index);  
	                            if(ret.code == 1){
	                            	Layer.closeAll();
	                            	$('.layui-layer-btn1').click();
	                                Toastr.success('删除栏目成功');
	                                getTree();
	                            } else {
									console.log(ret);
	                                Toastr.error(ret.msg);
	                            }                            
	                         }
	                      });
	                   }, function(){
	                    	
	                });     		
	        	})

            },
            second: function () {
                // 表格2
                var table2 = $("#table2");
                table2.bootstrapTable({
                    url: 'article/index',
                    extend: {
                        index_url: 'article/index',
                        add_url: 'article/add',
                        edit_url: 'article/edit',
                        del_url: 'article/del',
                        multi_url: '',
                        table: '',
                    },
                    toolbar: '#toolbar2',
                    sortName: 'id',
                    search: false,
                    columns: [
                        [
                            {field: 'column_id', title: __('column_id'), visible: false},
							{field: 'state', checkbox: true},
                            {field: 'id', title: 'ID'},
                            {field: 'title', title: __('Title')},
							{field: 'thumbnail', title: __('Thumbnail'), operate: false, events: Table.api.events.image, formatter: Table.api.formatter.image},
                            {field: 'columns_text', title: __('Column_id')},							
                            {field: 'topic', title: __('Topic')},
							{field: 'flag', title: __('Flag'), searchList: Config.flagList, operate:'FIND_IN_SET', formatter: Table.api.formatter.label},
                            {field: 'createtime', title: __('Createtime'), formatter: Table.api.formatter.datetime, operate: 'RANGE', addclass: 'datetimerange', sortable: true},
							{field: 'operate', title: __('Operate'), table: table2, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                        ]
                    ]
                });

                // 为表格2绑定事件
                Table.api.bindevent(table2);
            }
        },
		add: function () {
            Controller.api.bindevent();
            $(document).on("fa.event.appendfieldlist", ".btn-append", function(){
                Form.events.selectpage($(".fieldlist"));
            });
            Template.helper("Fast", Fast);
            $(document).on("fa.event.appendfieldlist", "#second-table .btn-append", function (e, obj) {                
                Form.events.selectpage(obj);  	//绑定动态下拉组件                
                Form.events.datetimepicker(obj);//绑定日期组件                
				Form.events.faupload(obj);		//绑定上传组件
                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
        },
		edit: function () {
            Controller.api.bindevent();
            $(document).on("fa.event.appendfieldlist", ".btn-append", function(){
                Form.events.selectpage($(".fieldlist"));
            });
            Template.helper("Fast", Fast);
            $(document).on("fa.event.appendfieldlist", "#second-table .btn-append", function (e, obj) {                
                Form.events.selectpage(obj);  	//绑定动态下拉组件                
                Form.events.datetimepicker(obj);//绑定日期组件                
				Form.events.faupload(obj);		//绑定上传组件
                //上传成功回调事件，变更按钮的背景
                $(".upload-image", obj).data("upload-success", function (data) {
                    $(this).css("background-image", "url('" + Fast.api.cdnurl(data.url) + "')");
                })
            });
        },
		api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
				//全选和展开
                $(document).on("click", "#checkall", function () {
                    $("#treeview").jstree($(this).prop("checked") ? "check_all" : "uncheck_all");
                });
                $(document).on("click", "#open_all, #close_all", function (e) {
					var id = e.target.id;
					$(this).attr('id', id == 'open_all' ? 'close_all' : 'open_all');
					$(this).attr('title', id == 'open_all' ? '收回全部栏目' : '展开全部栏目');
					
					if(id == 'open_all'){
						$(this).removeClass("fa fa-chevron-right");
						$(this).addClass("fa fa-chevron-down");
					} else {						
						$(this).removeClass("fa fa-chevron-down");
						$(this).addClass("fa fa-chevron-right");
					}
					
                    $("#treeview").jstree(id);
                });
            },
			rendertree: function (content) {
                $("#treeview")
					.on('redraw.jstree', function (e) {
							//$('#treeview').jstree("open_all");
                            $(".layer-footer").attr("domrefresh", Math.random());
                        })
	                .jstree({
	                    "themes": {"stripes": true},
	                    "checkbox": {
	                        "keep_selected_style": false,
	                    },
	                    "types": {
	                        "root": {
	                            "icon": "fa fa-folder-open",
	                        },
	                        "menu": {
	                            "icon": "fa fa-folder-open",
	                        },
	                        "file": {
	                            "icon": "fa fa-file-o",
	                        }
	                    },
	                    "plugins": ["types"],
	                    "core": {
	                        'check_callback': true,
	                        "data": content
	                    }
	                });
            }
        }
    };
    return Controller;
});
